import { Request } from '../../models/request.model';
import { StorageService } from '../../services/storage.service';

/**
 * 已保存请求管理类
 * 负责显示和管理已保存的请求
 */
export class SavedRequestsManager {
    private savedRequestsList: HTMLDivElement;
    private emptyState: HTMLDivElement;
    private searchInput: HTMLInputElement;
    private savedRequests: Request[] = [];
    private onRequestSelect: (request: Request) => void;
    private confirmDialog: HTMLDivElement | null = null;

    /**
     * 构造函数
     * @param onRequestSelect 请求选择处理函数
     */
    constructor(onRequestSelect: (request: Request) => void) {
        this.onRequestSelect = onRequestSelect;
        this.savedRequestsList = document.getElementById('saved-requests-list') as HTMLDivElement;
        this.emptyState = this.savedRequestsList.nextElementSibling as HTMLDivElement;
        this.searchInput = document.getElementById('search-saved-requests') as HTMLInputElement;
        
        // 添加搜索事件监听
        this.searchInput.addEventListener('input', () => this.filterRequests());

        // 加载保存的请求
        this.loadSavedRequests();
    }

    /**
     * 加载保存的请求
     */
    public async loadSavedRequests(): Promise<void> {
        try {
            // 清空列表
            this.savedRequestsList.innerHTML = '';

            // 获取保存的请求
            this.savedRequests = await StorageService.getSavedRequests();

            if (this.savedRequests.length === 0) {
                // 显示空状态
                this.emptyState.style.display = 'block';
                return;
            }

            // 应用当前搜索过滤
            this.filterRequests();
        } catch (error) {
            console.error('加载保存的请求时出错:', error);
        }
    }
    
    /**
     * 根据搜索条件过滤请求
     */
    private filterRequests(): void {
        // 清空列表
        this.savedRequestsList.innerHTML = '';
        
        const searchTerm = this.searchInput.value.toLowerCase().trim();
        
        // 过滤请求
        const filteredRequests = searchTerm ? 
            this.savedRequests.filter(request => 
                (request.name && request.name.toLowerCase().includes(searchTerm)) || 
                request.url.toLowerCase().includes(searchTerm) ||
                request.method.toLowerCase().includes(searchTerm)
            ) : 
            this.savedRequests;
            
        if (filteredRequests.length === 0) {
            // 显示空状态
            this.emptyState.style.display = 'block';
            this.emptyState.textContent = searchTerm ? 
                '没有找到匹配的请求' : 
                '没有保存的请求';
            return;
        }
        
        // 隐藏空状态
        this.emptyState.style.display = 'none';
        
        // 添加请求到列表
        filteredRequests.forEach(request => {
            const requestItem = this.createRequestItem(request);
            this.savedRequestsList.appendChild(requestItem);
        });
    }

    /**
     * 创建请求项元素
     * @param request 请求对象
     * @returns 请求项元素
     */
    private createRequestItem(request: Request): HTMLDivElement {
        const item = document.createElement('div');
        item.className = 'saved-request-item';

        // 方法
        const methodDiv = document.createElement('div');
        methodDiv.className = 'saved-method';
        const methodBadge = document.createElement('span');
        methodBadge.className = `method-badge ${request.method.toLowerCase()}`;
        methodBadge.textContent = request.method;
        methodDiv.appendChild(methodBadge);
        item.appendChild(methodDiv);

        // 名称
        const nameDiv = document.createElement('div');
        nameDiv.className = 'saved-name';
        nameDiv.textContent = request.name || '未命名请求';
        nameDiv.title = request.name || '未命名请求';
        item.appendChild(nameDiv);

        // URL
        const urlDiv = document.createElement('div');
        urlDiv.className = 'saved-url';
        urlDiv.textContent = request.url;
        urlDiv.title = request.url;
        item.appendChild(urlDiv);

        // 操作
        const actionsDiv = document.createElement('div');
        actionsDiv.className = 'saved-actions';

        // 调试按钮
        const debugButton = document.createElement('button');
        debugButton.className = 'debug-button';
        debugButton.textContent = '调试';
        debugButton.title = '在调试视图中打开此请求';
        debugButton.addEventListener('click', () => {
            this.onRequestSelect(request);
        });
        actionsDiv.appendChild(debugButton);

        // 删除按钮
        const deleteButton = document.createElement('button');
        deleteButton.className = 'delete-button';
        deleteButton.textContent = '删除';
        deleteButton.title = '删除此请求';
        deleteButton.addEventListener('click', () => {
            this.showConfirmDialog(
                `确定要删除请求 "${request.name || '未命名请求'}" 吗？`,
                async () => {
                    await StorageService.deleteSavedRequest(request.id || '');
                    await this.loadSavedRequests();
                    this.showNotification('已删除请求', 'success');
                }
            );
        });
        actionsDiv.appendChild(deleteButton);

        item.appendChild(actionsDiv);

        return item;
    }
    
    /**
     * 显示确认对话框
     * @param message 确认消息
     * @param onConfirm 确认回调
     */
    private showConfirmDialog(message: string, onConfirm: () => void): void {
        // 移除现有对话框
        if (this.confirmDialog) {
            document.body.removeChild(this.confirmDialog);
        }
        
        // 创建对话框遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'dialog-overlay';
        
        // 创建对话框
        this.confirmDialog = document.createElement('div');
        this.confirmDialog.className = 'confirm-dialog';
        
        // 添加消息
        const messageElement = document.createElement('p');
        messageElement.className = 'dialog-message';
        messageElement.textContent = message;
        this.confirmDialog.appendChild(messageElement);
        
        // 添加按钮容器
        const buttonsContainer = document.createElement('div');
        buttonsContainer.className = 'dialog-buttons';
        
        // 取消按钮
        const cancelButton = document.createElement('button');
        cancelButton.className = 'dialog-button cancel-button';
        cancelButton.textContent = '取消';
        cancelButton.addEventListener('click', () => {
            document.body.removeChild(overlay);
            document.body.removeChild(this.confirmDialog!);
            this.confirmDialog = null;
        });
        
        // 确认按钮
        const confirmButton = document.createElement('button');
        confirmButton.className = 'dialog-button confirm-button';
        confirmButton.textContent = '确定';
        confirmButton.addEventListener('click', () => {
            document.body.removeChild(overlay);
            document.body.removeChild(this.confirmDialog!);
            this.confirmDialog = null;
            onConfirm();
        });
        
        // 添加按钮到容器
        buttonsContainer.appendChild(cancelButton);
        buttonsContainer.appendChild(confirmButton);
        this.confirmDialog.appendChild(buttonsContainer);
        
        // 添加到文档
        document.body.appendChild(overlay);
        document.body.appendChild(this.confirmDialog);
        
        // 聚焦确认按钮
        confirmButton.focus();
    }
    
    /**
     * 显示通知提示
     * @param message 提示消息
     * @param type 提示类型
     */
    private showNotification(message: string, type: 'success' | 'error'): void {
        // 检查是否已存在通知元素
        let notification = document.getElementById('notification');
        if (!notification) {
            // 创建通知元素
            notification = document.createElement('div');
            notification.id = 'notification';
            document.body.appendChild(notification);
        }
        
        // 设置样式和消息
        notification.className = `notification ${type}`;
        notification.textContent = message;
        
        // 显示通知
        notification.classList.add('show');
        
        // 3秒后自动隐藏
        setTimeout(() => {
            notification.classList.remove('show');
        }, 3000);
    }
} 